package com.fingersoft.feature.remotefile;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import androidx.annotation.Nullable;

import com.fingersoft.api.ApiUtils;
import com.fingersoft.app.bean.AppConfigInfo;
import com.fingersoft.business.BusinessContext;
import com.fingersoft.common.ICallback;
import com.fingersoft.feature.filemanager.dao.FileDaoUtils;
import com.fingersoft.feature.filemanager.dao.bean.FileBean;
import com.fingersoft.feature.filemanager.ui.SelectfolderActivity;
import com.fingersoft.im.MyApplication;
import com.fingersoft.im.api.base.BaseModelCallback2;
import com.fingersoft.im.api.base.BaseResponse2;
import com.fingersoft.remotefile.IRemotefileContext;
import com.fingersoft.remotefile.ui.H5FilePreviewActivity;
import com.lzy.okgo.request.BaseRequest;

import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.util.HashMap;

import cn.fingersoft.io.rong.imkit.utils.MyFileTypeUtils;
import cn.fingersoft.io.rong.imkit.utils.FileTypeUtils;
import okhttp3.Call;
import okhttp3.Response;

public class SealRemoteContext implements IRemotefileContext {
    private final MyApplication application;
    protected AppConfigInfo appConfigInfo;
    public SealRemoteContext(MyApplication application) {
        appConfigInfo=(AppConfigInfo)getConfig(application);
        this.application = application;
    }

    @Override
    public boolean appIsInBackground() {
        return this.application.checkApp2Background();
    }

    public Object getConfig(Context context) {
        return BusinessContext.Companion.getAppConfigInfo();
    }
    @Override
    public  int  getFileTypeImgId(String fileName){
        return MyFileTypeUtils.getInstance().fileTypeImageId(fileName);
    }

    @Override
    public Intent getOpenFileIntent(String fileName, String fileSavePath) {
        return FileTypeUtils.getOpenFileIntent(fileName, fileSavePath);
    }

    @Override
    public void saveTomyfile(@Nullable String name, long size, @Nullable String url, @Nullable String path) {
        try {
            FileBean bean = new FileBean();
            bean.setId(url);
            bean.setLocalPath(path);
            bean.setName(name);
            bean.setSize(size);
            bean.setTime(System.currentTimeMillis());
            bean.setType(FilenameUtils.getExtension(name));
            FileDaoUtils.Companion.getInstance().saveDownloadFile(bean);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean isApp_file_local_storage() {
        return appConfigInfo.isApp_file_local_storage();
    }

    @Override
    public boolean isYunpan() {
        return appConfigInfo.isYunpan();
    }

    @Override
    public void movetoyun(Context context,String name,String url) {
        SelectfolderActivity.startSelectfolderActivity(context, "0", name, Uri.parse(url), true);
    }

    @Override
    public void deleteFile(String id) {
        FileDaoUtils.Companion.getInstance().deleteMyFilesById(id);
    }

    @Override
    public void sendMyFile(Context context, File file, String type) {
        BusinessContext.Companion.getIm().sendFileMessage(context, file, type);
    }

    @Override
    public boolean isApp_preview_file() {
        return appConfigInfo.isApp_preview_file();
    }

    @Override
    public void getPreviewurl(Context context, String path, HashMap<String, String> params, ICallback callback) {
        final ApiUtils apiUtils = new ApiUtils(context);
        BusinessContext.Companion.getApi().post(path, params, new BaseModelCallback2<BaseResponse2>(BaseResponse2.class) {
            @Override
            public void onSuccess(BaseResponse2 baseResponse2, Call call, Response response) {
                super.onSuccess(baseResponse2, call, response);
                if (apiUtils.showApiSucceedErrorToast(baseResponse2)) {
                    callback.onError();
                    return;
                }
                callback.onSuccess(baseResponse2.getData());
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                callback.onError();
            }

            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
            }

            @Override
            public void onAfter(BaseResponse2 baseResponse2, Exception e) {
                super.onAfter(baseResponse2, e);
            }
        });
    }

    @Override
    public void previewFileByWebview(Context context, String url, String name) {
        BusinessContext.Companion.getWebViev().openWebView(context,url,name);
    }

    @Override
    public String getShare_module() {
       return appConfigInfo.getShare_module();
    }

    @Override
    public boolean hasfileInMyFile(String id) {
        return FileDaoUtils.Companion.getInstance().getMyFilesById(id)==null?false:true;
    }

    @Override
    public void openfile(String md5,String name, String type,long size, String url) {
//        boolean autoDownLoad = true;
////        if (content.getSize() >= 5 * 1024 * 1024) {
////            //大于等于5M的文件由融云下载页面处理
////            autoDownLoad = false;
////        }
//        //小文件直接下载或打开
//       Message message=new Message();
//       message.setMessageDirection(Message.MessageDirection.RECEIVE);
//       message.setConversationType(Conversation.ConversationType.NONE);
//        File targetFile = new File("/storage/emulated/0/1.text");
//        RandomAccessFile raf = null;
//        try {
//            raf = new RandomAccessFile(targetFile, "rw");
//            // 将文件记录指针移动到最后  
//            raf.seek(targetFile.length());
//            // 输出文件内容  
//            raf.write("上传文件".getBytes());
//            raf.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        FileMessage fileMessage = FileMessage.obtain(Uri.parse("file://" + targetFile.getPath()));
//        fileMessage.setName(name);
//        fileMessage.setSize(size);
//        fileMessage.setLocalPath(Uri.parse(url));
//        fileMessage.setFileUrl(Uri.parse(url));
//        message.setContent(fileMessage);
        Intent intent = new Intent(application, H5FilePreviewActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.putExtra("messageUId", message.getUId());
//        intent.putExtra("sentTime", message.getSentTime());
//        intent.putExtra("TargetId", message.getTargetId());
//        intent.putExtra("ConversationType", message.getConversationType());
//        intent.putExtra("FileMessage", fileMessage);
//        intent.putExtra("Message", message);
//        intent.putExtra("Progress", 0);
//        intent.putExtra("IsOutoDownLoad", autoDownLoad);
        intent.putExtra("md5", md5);
        intent.putExtra("name", name);
        intent.putExtra("type", type);
        intent.putExtra("size", size);
        intent.putExtra("url", url);
        application.startActivity(intent);
    }
}
